/**
* Description: 编辑胸牌弹窗
*
* Created by hrx on 2023/9/18
*/
<template>
  <div class="edit-badge">
    <el-dialog
      :title="mode == 'add' ? '创建胸牌' : '编辑胸牌'"
      width="660px"
      v-model="dialogFormVisible"
      :append-to-body="true"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" class="form">
        <el-form-item
          label-width="120px"
          label="胸牌编号"
          prop="breastpieceCode"
        >
          <el-input
            placeholder="请输入"
            style="width: 360px; height: 36px"
            v-model="form.breastpieceCode"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit()">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">

import type {FormInstance, FormRules} from 'element-plus'
import {reactive, ref, watch} from "vue";
import {addBadgeApi, type badgeDetailDTO} from "@/api/badge";
import {ElMessage} from "element-plus";
const emit = defineEmits(['afterSubmit']);


const dialogFormVisible = ref<boolean>(false)
const mode = ref<string>('add')
const formRef = ref<FormInstance>()
const form = reactive<badgeDetailDTO>({
  breastpieceCode: '',
  id: 0
})
const validBreastpieceCode = (rule: any, value: any, callback: any) => {
  if (value == '') {
    callback(new Error('请输入胸牌编号'));
  } else if (value.length > 30) {
    callback(new Error('只能输入1~30个字符'));
  } else {
    callback();
  }
}
const ruleForm = reactive({
  breastpieceCode: '',
})
const rules = reactive<FormRules<typeof ruleForm>>({
  breastpieceCode: [{required: true, validator: validBreastpieceCode, trigger: 'change'}],
})

watch([dialogFormVisible],(newVal: Array<any>) => {
  if (newVal[0] === false) {
     formRef?.value?.resetFields();
  }
})

const submit = () => {
  if (!formRef) return
  formRef.value?.validate( async (valid) => {
    if (valid) {
      let res = await addBadgeApi(form);
      if(res.data.code == 0) {
        ElMessage.success('创建成功')
        emit('afterSubmit', '')
        dialogFormVisible.value = false;
      }
    } else {
      return false
    }
  })
}

defineExpose({
  dialogFormVisible,
  mode
})

</script>

<style scoped>

</style>